//
//  YGSearchResultController.m
//  SunshineMall
//
//  Created by 张艳江 on 2018/11/1.
//  Copyright © 2018年 张艳江. All rights reserved.
//

#import "SCSearchResultController.h"
#import "SCSearchTitleView.h"
#import "SCIntegralGoodsCell.h"
#import "SCSearchTagView.h"

@interface SCSearchResultController ()<UITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) SCSearchTitleView *searchTitleView;//搜索栏
@property (nonatomic, strong) SCSearchTagView   *searchTagView;
@property (nonatomic, strong) NSMutableArray    *historyArray;
@property (nonatomic, strong) UICollectionView  *collectionView;
@property (nonatomic, strong) NSMutableArray    *dataArray;
@property (nonatomic, strong) NSString          *order;
@property (nonatomic, assign) int pageIndex;
@property (nonatomic, assign) BOOL isSearch;


@end

@implementation SCSearchResultController

#pragma mark - LazyLoad
- (NSMutableArray *)historyArray{
    if (!_historyArray) {
        _historyArray = [NSKeyedUnarchiver unarchiveObjectWithFile:KHistorySearchPath];
        if (!_historyArray) {
            self.historyArray = [NSMutableArray array];
        }
    }
    return _historyArray;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.minimumLineSpacing = 7;
        layout.minimumInteritemSpacing = 7;
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        CGFloat w = (kScreenW- 27)/2.0;
        layout.itemSize = CGSizeMake(w, w+82);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 40.5, kScreenW, kScreenH - kTopHeight - 40.5) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = BGColor;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [_collectionView registerNib:[UINib nibWithNibName:@"JSGoodsCell" bundle:nil] forCellWithReuseIdentifier:@"JSGoodsCellID"];
    }
    return _collectionView;
}
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.lineView.hidden = NO;
    self.view.backgroundColor = BGColor;
    
    //设置表格
    [self setUpCollectionView];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"back"] target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithButtonFrame:CGRectMake(0, 0, 44, 44) title:@"搜索" color:[UIColor blackColor] font:SCFont(15) target:self action:@selector(clickSearch)];
    
    self.isSearch = NO;
    //设置搜索
    [self setupSearchTitleView];
    [self.view addSubview:self.collectionView];
    //请求数据
    self.pageIndex = 1;
    [self requestDoodsData:self.searchStr];
}
- (void)setUpCollectionView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    CGFloat w = (kScreenW-50)/3.0f;
    layout.itemSize = CGSizeMake(w, w*79/105+45);
    layout.sectionInset = UIEdgeInsetsMake(12, 12, 12, 12);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0.5, kScreenW, kScreenH-kTopHeight) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.collectionView registerNib:[UINib nibWithNibName:@"SCIntegralGoodsCell" bundle:nil] forCellWithReuseIdentifier:@"SCIntegralGoodsCellID"];
    [self.view addSubview:self.collectionView];
}
- (void)loadMoreData{
    self.pageIndex++;
    [self requestDoodsData:self.searchStr];
}
- (void)back{
    if (self.isSearch == NO) {
        if (self.isGiftApp == YES) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
        }
    }else{
        self.isSearch = NO;
        [self.searchTitleView.searchTextField resignFirstResponder];
        [self.searchTagView removeFromSuperview];
    }
}
- (void)clickSearch{
    
    if (self.searchTitleView.searchTextField.text.length == 0) {
        [SVProgressHUD showImage:nil status:@"请输入搜索内容"];
        return;
    }
    self.isSearch = NO;
    [self.searchTitleView.searchTextField resignFirstResponder];
    [self.searchTagView removeFromSuperview];
    [self setSearchResultWithStr:self.searchTitleView.searchTextField.text];
}

- (void)setupSearchTitleView{
    self.searchTitleView = [[SCSearchTitleView alloc]initWithFrame:CGRectMake(5+44, kStatusBarHeight+7, kScreenW-(5+44)-10-44, 30)];
    self.searchTitleView.searchTextField.text = self.searchStr;
    self.searchTitleView.searchTextField.delegate = self;
    self.navigationItem.titleView = self.searchTitleView;
}
#pragma mark - searchTextField的代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    self.isSearch = YES;
    [self setSearchTagView];
    return YES;
}
- (void)setSearchTagView{
    self.searchTagView = [[SCSearchTagView alloc] initWithFrame:CGRectMake(0, 0.5, kScreenW, kScreenH - kTopHeight) hotArray:self.hotArray historyArray:self.historyArray];
    WeakSelf;
    self.searchTagView.tapAction = ^(NSString *str) {
        weakSelf.isSearch = NO;
        [weakSelf.searchTitleView.searchTextField resignFirstResponder];
        [weakSelf.searchTagView removeFromSuperview];
        [weakSelf setSearchResultWithStr:str];
    };
    [self.view addSubview:self.searchTagView];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length == 0) {
        [SVProgressHUD showImage:nil status:@"请输入搜索内容"];
        return NO;
    }
    self.isSearch = NO;
    [textField resignFirstResponder];
    [self.searchTagView removeFromSuperview];
    [self setSearchResultWithStr:textField.text];
    return YES;
}
#pragma mark - 请求搜索
- (void)setSearchResultWithStr:(NSString *)str{
    self.searchTitleView.searchTextField.text = str;
    [self setHistoryArrWithStr:str];
    //请求数据
    self.pageIndex = 1;
    [self requestDoodsData:str];
}
#pragma mark - 添加到历史搜索
- (void)setHistoryArrWithStr:(NSString *)str{
    for (int i = 0; i < self.historyArray.count; i++) {
        if ([self.historyArray[i] isEqualToString:str]) {
            [self.historyArray removeObjectAtIndex:i];
            break;
        }
    }
    [self.historyArray insertObject:str atIndex:0];
    [NSKeyedArchiver archiveRootObject:self.historyArray toFile:KHistorySearchPath];
}
#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SCIntegralGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCIntegralGoodsCellID" forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
}
#pragma mark - 请求数据
- (void)requestDoodsData:(NSString *)searchStr{
    
    NSString *type;
    NSString *url;
    if (self.isGiftApp == YES) {
        type = @"gift_name";
        url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GiftApp&a=App_search"];
    }else{
        type = @"goods_name";
        url = [MyTool splicingWithUrl:@"admin.php?g=System&c=GoodsApp&a=App_search"];
    }
    
    NSDictionary *dict = @{type:searchStr,
                           @"size":@"15",
                           @"pagenow":@(self.pageIndex)};
    NSLog(@"===%@",dict);
    if (self.pageIndex == 1) {
        [SVProgressHUD showWithStatus:@"加载中..."];
    }
    [[NetworkRequestTool sharedNetworkTool] GET:url parameters:dict finished:^(id result, NSString *error) {
        [SVProgressHUD dismiss];
        if (self.pageIndex == 1) {
            [self.dataArray removeAllObjects];
        }
        NSArray *tempArray = [SCModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"data"]];
        [self.dataArray addObjectsFromArray:tempArray];
        [self.collectionView reloadData];
    }];
}

@end
